//app.js
var com = require("./utils/common.js");
var util = require("./utils/util.js");
// var mta = require('./utils/mta_analysis.js');
var more = 0;
App({
  onLaunch: function (options) {
    var that = this;
    wx.getSystemInfo({
      success: function (res) {
        that.systemInfo = res;
      }
    })
    // //腾讯分析
    // mta.App.init({
    //   "appID": "500650129",
    // });
    var ver = that.checkVersion();
    if (ver) {
      that.wxLogin();
      that.loadFontfun();
    }
    wx.setStorageSync('lookAuth', false)
  },
  //微信登陆
  wxLogin() {
    var that = this;
    wx.login({
      success: res => {
        var getpid = wx.getStorageSync('pid');
        // 发送 res.code 到后台换取 openId
        that.register(res.code, getpid);
      }
    })
    wx.onNetworkStatusChange(function (res) {
      if (res.networkType == 'none') {
        that.showToast('网络连接断开');
      }
    })
  },
  // 扫码
  scanning: function (success) {
    var that = this;
    wx.scanCode({
      success: (res) => {
        console.log(res)
        var values = '';
        if (res.result.indexOf('device_no=') > -1) { //设备码
          var strs = res.result.split('?device_no=');
          values = strs[1];
        } else { //主板码
          var code = res.result.split(';')
          if (!util.isExitsVariable(code) || code.length == 0) {
            that.showToast('扫码失败');
            return false;
          }
          if (code[2] && code[2].indexOf(":") != -1) {
            var val = code[2].split(':');
            if (!util.isExitsVariable(val) || val.length == 0) {
              that.showToast('扫码失败');
              return false;
            }
            values = val[1];
          } else {
            values = code[0];
          }
        }
        success(values);

      },
      fail: (res) => {
        that.showToast('扫码失败，请重试！');
      }
    })
  },

  //检查版本
  checkVersion() {
    var that = this;
    const version = wx.getSystemInfoSync().SDKVersion
    console.log(version, "version")
    if (that.compareVersion(version, '1.6.8') < 0) {
      // 如果希望用户在最新版本的客户端上体验您的小程序，可以这样子提示
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低，无法使用部分功能，请升级到最新微信版本后重试。'
      })
      return false;
    }
    return true;
  },
  compareVersion(v1, v2) {
    v1 = v1.split('.')
    v2 = v2.split('.')
    const len = Math.max(v1.length, v2.length)

    while (v1.length < len) {
      v1.push('0')
    }
    while (v2.length < len) {
      v2.push('0')
    }
    for (let i = 0; i < len; i++) {
      const num1 = parseInt(v1[i])
      const num2 = parseInt(v2[i])

      if (num1 > num2) {
        return 1
      } else if (num1 < num2) {
        return -1
      }
    }

    return 0
  },

  //字体下载
  loadFontfun() {
    var that = this;
    return false;
    wx.loadFontFace({
      family: 'huawen',
      source: 'url("' + that.globalData._network_path + 'censcbk.ttf")',
      success: function (res) {
        console.log('>>>>', res);
      },
      fail: function (res) {
        more += 1;
        if (more >= 5) {
          return false;
        }
        that.loadFontfun(); //再次调用字体 
      }
    })
  },
  //跳转到登陆页面
  redirectLogin() {
    var that = this;
    //避免重复登录
    var is_login = wx.getStorageSync('is_login');
    if (is_login) {
      return false;
    }
    wx.setStorageSync('is_login', true);
    that.showModal("", "您还未登录，请先登录", function () {
      wx.navigateTo({
        url: '/pages/user/login/login',
      })
    }, function () {
      wx.setStorageSync('is_login', false);
    });
  },

  //获取openid,session_key最终生成token返回
  register: function (code, getpid) {
    var that = this;
    var phoneInfo = wx.getSystemInfoSync();
    var way = wx.getStorageSync('way');
    that.ajax({
      url: 'User/User/register',
      data: {
        code: code,
        pid: getpid,
        way: way,
        client_device_brand: phoneInfo.brand, //是 |String |品牌
        client_device_model: phoneInfo.model, //是 |String |型号 
        clinet_device_wx_version: phoneInfo.version, //是  |微信版本
        clinet_device_system_version: phoneInfo.system, //是  |String |操作系统版本 
        clinet_device_base_version: phoneInfo.SDKVersion, //是  |String |客户端基础库版本
        client_device_platform: phoneInfo.platform, //是  |String |客户端平台 
      },
      success: function (res) {
        if (res.data.code == 1000 || res.data.code == -1100) {
          wx.setStorageSync('openid', res.data.data.openid);
        } else if (res.data.code == -1101 || res.data.code == -1000) {
          wx.setStorageSync('is_login', false);
          that.redirectLogin();
        }
      }
    })
  },

  //保存formId
  saveFormId: function (formId) {
    console.log(formId);
    var that = this;
    var openid = wx.getStorageSync('openid');
    that.ajax({
      url: 'Common/Wx/saveFormId',
      data: {
        openid: openid,
        formId: formId
      },
      success: function (res) {
        console.log(res);
        if (res.data.code == 1000) {
          console.log('保存formId成功');
        } else {
          console.log('保存formId失败')
        }

      }
    })
  },

  //重新绑定用户信息必须加手机号码
  bindGetnewToken(types, simcode, page) {
    var that = this;
    var phone = wx.getStorageSync('phone');
    var openid = wx.getStorageSync('openid');
    var pid = wx.getStorageSync('pid');
    var way = wx.getStorageSync('way');
    var promoter = wx.getStorageSync('promoter');//推广商ID
    var channel = wx.getStorageSync('channel');//渠道ID
    console.log(pid, "pid");
    var phoneInfo = wx.getSystemInfoSync();
    console.log(phoneInfo);
    that.ajax({
      url: 'User/User/bind',
      method: "POST",
      data: {
        tel: phone,
        bind_type: types,
        code: simcode,
        openid: openid,
        pid: pid,
        way: way,
        channel: channel,
        promoter: promoter,
        client_device_brand: phoneInfo.brand, //是 |String |品牌
        client_device_model: phoneInfo.model, //是 |String |型号 
        clinet_device_wx_version: phoneInfo.version, //是  |微信版本
        clinet_device_system_version: phoneInfo.system, //是  |String |操作系统版本 
        clinet_device_base_version: phoneInfo.SDKVersion, //是  |String |客户端基础库版本
        client_device_platform: phoneInfo.platform, //是  |String |客户端平台 
      },
      success: function (res) {
        if (res.data.code == -1105) {
          wx.setStorageSync('is_login', false);
          that.redirectLogin();
        }
        wx.hideLoading();
        wx.setStorageSync('token', res.data.data.token);
        wx.setStorageSync('user_id', res.data.data.user_id);
        that.showToast(res.data.message, "none", 1000, function () { });
        if (res.data.code == 1000) {
          // 更新用户地址
          that.updateAddress();
          wx.navigateBack({
            delta: page
          })
        }
      }
    })
  },

  // 更新用户地址
  updateAddress: function () {
    var that = this;
    var country = wx.getStorageSync('country');
    var province = wx.getStorageSync('province');
    var city = wx.getStorageSync('city');
    var area = wx.getStorageSync('area');
    var area_id = wx.getStorageSync('area_id');
    that.ajax({
      url: 'User/User/editAddress',
      data: {
        country: country,
        province: province,
        city: city,
        area: area,
        id: area_id,
        address_is_update: 2
      },
      success: function (res) {
        //console.log('更新用户地址结果', res)
      }
    })
  },

  //获取登陆状态
  loginStatus(success, fail) {
    var that = this;
    //返回Promise对象
    return new Promise(
      function (resolve) {
        var token = wx.getStorageSync('token');
        wx.request({
          method: "POST",
          url: that.globalData._url + 'User/User/loginStatus',
          header: {
            'token': token // 默认值
          },
          success: (resolve) => {
            console.log('请求结果', resolve);
            if (resolve.data.code == 1000) {
              success(resolve);
            } else if (resolve.data.code == -1006) {
              wx.showModal({
                title: '',
                content: resolve.data.message,
                confirmText: '联系客服',
                cancelText: '切换账号',
                cancelColor: '#6CA9FF',
                success(res) {
                  if (res.confirm) {
                    wx.navigateTo({
                      url: '/pages/user/helpCenter/helpCenter',
                    })
                  } else if (res.cancel) {
                    wx.navigateTo({
                      url: '/pages/user/login/login',
                    })
                  }
                },
              })
            } else {
              fail(resolve);
            }
          },
          error: (resolve) => {
            fail(resolve);
          }
        })
      })
  },

  //生成页面二维码
  createQrcode(query, page, success) {
    var that = this;
    that.ajax({
      url: 'Common/Wx/getPageQr',
      data: {
        query: query,
        page: page
      },
      success: function (res) {
        var result = res.data.data.all_url;
        success(result)
      }
    })
  },
  //跳转到其他小程序
  navigateToMiniProgram(appId, path, extraData = {}, envVersion ='release') {
    wx.navigateToMiniProgram({
      appId: appId,
      path: path,
      extraData: extraData,
      envVersion: envVersion,//trial体验版release正式版
      success(res) {
        console.log('success', res);
      },
      fail(e) {
        console.log('error', e);
      }
    })
  },

  //ajax 请求
  ajax(model) {
    var that = this;
    if (util.isExitsVariable(model.load)) {
      var msg = "加载中";
      if (util.isExitsVariable(model.msg)) {
        msg = model.msg;
      }
      wx.showLoading({
        title: msg,
      })
    }
    if (!util.isExitsVariable(model.method)) {
      model.method = "POST";
    }

    // 判断请求哪个接口
    if (model.url_type == 1) { // boss接口
      //拼接url
      if (model.url.indexOf("https://") == -1 && model.url.indexOf("http://") == -1) {
        model.url = this.globalData.boss_url + model.url;
      }
    } else {
      //拼接url
      if (model.url.indexOf("https://") == -1 && model.url.indexOf("http://") == -1) {
        model.url = this.globalData._url + model.url;
      }
    }

    //get参数拼接
    if (model.method == "get" && model.data !== undefined) {
      for (let k in model.data) {
        if (model.data[k].toString() !== '') {
          model.url = model.url + "&" + k + "=" + model.data[k];
        }
      }
      model.data = '';
    }

    //返回Promise对象
    return new Promise(
      function (resolve) {
        var token = wx.getStorageSync('token');
        wx.request({
          method: model.method,
          url: model.url,
          header: {
            'token': token, // 默认值
            'client': that.globalData.client,//终端，1微信版 2支付宝版 3百度版
            'company': that.globalData.company_id,//公司ID
            'role': that.globalData.role,//角色
          },
          data: model.data,
          success: (resolve) => {
            if (util.isExitsVariable(model.load)) {
              wx.hideLoading();
            }
            if (resolve.data.code == -1004) { //未登录 跳到登录去
              that.redirectLogin();
              return;
            }
            if (resolve.data.code == -1005) {
              wx.setStorageSync('is_login', false);
              that.redirectLogin();
              return; //登录过期
            }
            model.success(resolve);
          },
          error: () => {
            model.error('网络请求失败');
          }
        })
      }
    )
  },

  globalData: {
    company_id: 1,
    client: 1,//终端1微信 2支付宝
    role: 4,//角色 端1总后台 2运营 3行政 4用户 5工程
    userInfo: null,
    _network_path: 'https://qn.youheone.com/cloud_user_weapp_image/company_runquan/',
    water_user_appid: 'wx26e05a3010ad77d3',//滳滳用户端小程序APPID 测试环境:wx26e05a3010ad77d3 正式环境
    qi_niu_url: 'https://qn.youheone.com/',
    _url: 'https://yh.cqthesis.cn/',
    boss_url: 'https://test.cqthesis.cn/'
    //wx76e19f9eb5bcb658
  //  _url:'https://rqcrm.youheone.com/',
  //  boss_url: 'https://boss.youheone.com/'
   //wx241bdf1cffb21b83
  },

  //弹窗MODEL
  showModal(title = "提示", content = "", success = function () { }, cancel = function () { }) {
    wx.showModal({
      title: title,
      content: content,
      showCancel: true,
      success: function (res) {
        if (res.confirm) {
          success();
        } else if (res.cancel) {
          cancel();
        }
      }
    })
  },

  //弹窗toast
  showToast(title = "", icon = "none", duration = 1500, complete = function () { }) {
    wx.showToast({
      title: title ? title : '与服务器断开连接',
      icon: icon,
      duration: duration,
      mask: true,
      complete: function (res) {
        complete();
      }
    })
    return false;
  },

  /**
   * 系统信息
   */
  systemInfo: null, //系统信息
})